package handlers

import (
	"encoding/json"
	"fmt"
	"gitee.com/dreamwithouttrace/websocket-module/core"
	"gitee.com/dreamwithouttrace/websocket-module/transport"
	"net/http"
)

// APIHandler WebSocket API处理器
type APIHandler struct {
	transport *transport.Transport
	config    *core.Config
}

// NewAPIHandler 创建新的API处理器
func NewAPIHandler(transport *transport.Transport, config *core.Config) *APIHandler {
	return &APIHandler{
		transport: transport,
		config:    config,
	}
}

// Kick 踢出用户
func (h *APIHandler) Kick(w http.ResponseWriter, r *http.Request) {
	userID := r.URL.Query().Get("userId")
	if userID == "" {
		h.writeErrorResponse(w, "缺少用户ID", http.StatusBadRequest)
		return
	}

	// 解析用户ID
	var id int64
	if _, err := fmt.Sscanf(userID, "%d", &id); err != nil {
		h.writeErrorResponse(w, "无效的用户ID", http.StatusBadRequest)
		return
	}

	h.transport.Kick(id, "")
	h.writeSuccessResponse(w, "用户已被踢出")
}

// OnlineLists 获取在线用户列表
func (h *APIHandler) OnlineLists(w http.ResponseWriter, r *http.Request) {
	lists := h.transport.GetClientLists()
	h.writeJSONResponse(w, lists)
}

// OnlineInfo 获取在线用户信息
func (h *APIHandler) OnlineInfo(w http.ResponseWriter, r *http.Request) {
	userID := r.URL.Query().Get("id")
	if userID == "" {
		h.writeErrorResponse(w, "缺少用户ID", http.StatusBadRequest)
		return
	}

	// 解析用户ID
	var id int64
	if _, err := fmt.Sscanf(userID, "%d", &id); err != nil {
		h.writeErrorResponse(w, "无效的用户ID", http.StatusBadRequest)
		return
	}

	user := h.transport.GetClientInfo(id)
	if user == nil {
		h.writeErrorResponse(w, "用户不在线", http.StatusNotFound)
		return
	}

	h.writeJSONResponse(w, user)
}

// CheckContent 检查内容
func (h *APIHandler) CheckContent(w http.ResponseWriter, r *http.Request) {
	keyword := r.URL.Query().Get("keyword")
	if keyword == "" {
		h.writeErrorResponse(w, "缺少关键词", http.StatusBadRequest)
		return
	}

	// 这里可以添加内容检查逻辑
	result := h.checkContentKeyword(keyword)
	h.writeJSONResponse(w, map[string]interface{}{
		"keyword": keyword,
		"result":  result,
	})
}

// PostCheckContent POST方式检查内容
func (h *APIHandler) PostCheckContent(w http.ResponseWriter, r *http.Request) {
	if err := r.ParseForm(); err != nil {
		h.writeErrorResponse(w, "解析表单失败", http.StatusBadRequest)
		return
	}

	keyword := r.FormValue("keyword")
	if keyword == "" {
		h.writeErrorResponse(w, "缺少关键词", http.StatusBadRequest)
		return
	}

	// 这里可以添加内容检查逻辑
	result := h.checkContentKeyword(keyword)
	h.writeJSONResponse(w, map[string]interface{}{
		"keyword": keyword,
		"result":  result,
	})
}

// Statistics 获取统计信息
func (h *APIHandler) Statistics(w http.ResponseWriter, r *http.Request) {
	boy, girl, noSex := h.transport.OnlineUserInformationStatistics()
	total := boy + girl + noSex

	stats := &core.Statistics{
		Total: total,
		Boy:   boy,
		Girl:  girl,
		NoSex: noSex,
	}

	h.writeJSONResponse(w, stats)
}

// checkContentKeyword 检查内容关键词
func (h *APIHandler) checkContentKeyword(keyword string) map[string]interface{} {
	// 这里可以添加具体的内容检查逻辑
	// 示例实现：
	return map[string]interface{}{
		"is_sensitive": false,
		"level":        0,
		"message":      "内容检查通过",
	}
}

// writeJSONResponse 写入JSON响应
func (h *APIHandler) writeJSONResponse(w http.ResponseWriter, data interface{}) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"code": 0,
		"msg":  "success",
		"data": data,
	})
}

// writeSuccessResponse 写入成功响应
func (h *APIHandler) writeSuccessResponse(w http.ResponseWriter, message string) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"code": 0,
		"msg":  message,
		"data": nil,
	})
}

// writeErrorResponse 写入错误响应
func (h *APIHandler) writeErrorResponse(w http.ResponseWriter, message string, statusCode int) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(statusCode)
	json.NewEncoder(w).Encode(map[string]interface{}{
		"code": statusCode,
		"msg":  message,
		"data": nil,
	})
}
